<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function plant_info_list_page()
{
    @$output = drupal_render(drupal_get_form('plant_info_list_form'));
    return $output;
}

function plant_info_list_form($form, &$form_state)
{
    global $user;
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if (!empty($form_state['addr_id'])) {
        $form['#addr_id'] = $form_state['addr_id'];
    }
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }

        $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : '';
        _insert_date_selection_form($form, $form_state, 5, $init_year, '', false);
        if (get_user_role_name($user->uid) != '农户') {
        if (empty($form_state['farmer']) && empty($form['#addr_id'])) {
            $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
            $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
        }
        if(!empty($_GET['special_activities'])){
            $special_activities_title = get_special_activities_title($_GET['special_activities']);
        }
        $form['special_activities'] = array(
            '#type' => 'textfield',
            '#title' => '专项活动',
            '#size' => 32,
            '#maxlength' => 50,
            '#id'=>'special_activities_textfield',
            '#default_value' => $special_activities_title,
        );
    }
    $form['plant'] = _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    $fields = array(
        '' => '请选择',
        'plant_area' => '种植面积',
        'plant_space' => '株距',
        'row_space' => '行距',
        'seed_cost' => '种子开销',
        'fertilizer_cost' => '肥料开销',
        'pesticide_cost' => '农药开销',
        'machinery_cost' => '农机开销',
        'others_cost' => '其他开销',
        'general_yield' => '一般产量',
        'other_yield' => '其他收益',
    );
    numerical_range_search($form, $fields);
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');

    return $form;
}

function plant_info_list_form_validate($form, &$form_state)
{
}

function data_list_view_page(&$form = '', &$form_state = '')
{
    global $user;
    $output = '';
    //表头
    if (get_user_role_name($user->uid) === '农户') {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '农作物', 'class' => ['integrant essential plant_name'], 'field' => 'plant_name'),
            array('data' => '播种日期', 'class' => ['integrant essential sow_date'], 'field' => 'sow_date'),
            array('data' => '收获日期', 'class' => ['integrant essential harvest_date'], 'field' => 'harvest_date'),
            array('data' => '种植面积', 'class' => ['integrant essential break farm_area'], 'field' => 'farm_area'),
            array('data' => '操作', 'class' => ['essential more']),
        );
    } else {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
                array('data' => '地址', 'class' => ['essential province city county']),
            isset($form_state['farmer']) && !empty($form_state['farmer']) ? "" :
                array('data' => '农户姓名', 'class' => ['essential plant_info_name']),
            array('data' => '农作物', 'class' => ['essential plant_name'], 'field' => 'plant_name'),
            array('data' => '播种日期', 'class' => ['essential break sow_date'], 'field' => 'sow_date'),
            array('data' => '收获日期', 'class' => ['essential break harvest_date'], 'field' => 'harvest_date'),
            array('data' => '种植面积', 'class' => ['integrant essential break farm_area'], 'field' => 'farm_area'),
            array('data' => '操作', 'class' => ['essential more']),
        );
    }
    $query = db_select('plant_info', 'PI')->extend('PagerDefault')->extend('TableSort');
    $query->join('farmer', 'F', 'F.farmer_id=PI.farmer_id');
    $query->join('plant', 'P', 'P.plant_id=PI.plant_id');
    $query->join('addr', 'A', 'F.addr_id=A.addr_id');


        $datestr = '';
        if (!empty($form_state['values']['year'])) {//查询条件
            if ($form_state['values']['year']) {
                $datestr .= $form_state['values']['year'] . '-';
            }
        }
        if ($datestr) {
            $or = db_or()->condition('PI.sow_date', db_like($datestr) . '%', 'LIKE')->condition('PI.harvest_date', db_like($datestr) . '%', 'LIKE');
            $query->condition($or);
        }
    if (get_user_role_name($user->uid) === '农户') {
        $query->condition('PI.farmer_id', $user->uid);
    } else {
        //地址级别查询
        _address_search_conditon($query,$form_state);
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('PI.farmer_id', $form_state['values']['farmer']);
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('PI.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('PI.farmer_id', $form_state['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $form_state['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('PI.farmer_id', $form_state['values']['farmer_id'], '=');
        }
        if(!user_access('view all plant_info') && user_access('view own plant_info')){
            $query->condition('PI.author_uid',$user->uid, '=');
        }
        //专项活动
        if(!empty($form_state['values']['special_activities'])){
            $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
            if(!empty($special_activities_id)){
                $query->condition('PI.special_activities_id',$special_activities_id, '=');
            }else{
                $query->condition('PI.special_activities_id',0, '=');
            }
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('PI.special_activities_id',$_GET['special_activities'], '=');
    }
    if(!empty($form_state['values']['plant'])){
        $query->condition('PI.plant_id',get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false), '=');
    }

    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('PI.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('PI.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('PI.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('PI.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    $query->fields('PI');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('P', 'plant_name');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'farmer_id');
    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('PI.timestamp', 'DESC');
    }
    //统计
    $statQuery = $query->cloneQuery();
    $statQuery->addExpression('format(avg(PI.plant_area),2)','avg_plant_area');
    $statQuery->addExpression('format(sum(PI.plant_area),2)','sum_plant_area');
    $statQuery->addExpression('format(avg(PI.seed_cost),2)','avg_seed_cost');
    $statQuery->addExpression('format(avg(PI.fertilizer_cost),2)','avg_fertilizer_cost');
    $statQuery->addExpression('format(avg(PI.pesticide_cost),2)','avg_pesticide_cost');
    $statQuery->addExpression('format(avg(PI.machinery_cost),2)','avg_machinery_cost');
    $statQuery->addExpression('format(avg(PI.others_cost),2)','avg_others_cost');
    $statQuery->addExpression('format(avg(PI.general_yield),2)','avg_general_yield');
    $statQuery->addExpression('format(avg(PI.other_yield),2)','avg_other_yield');
    $statQuery->addExpression('count(*)','count');
    $statInfo = $statQuery->execute()->fetchObject();
    $form["#stat"]['#count'] = $statInfo->count;
    $form["#stat"]['#avg_plant_area'] = $statInfo->avg_plant_area;
    $form["#stat"]['#sum_plant_area'] = $statInfo->sum_plant_area;
    $form["#stat"]['#avg_seed_cost'] = $statInfo->avg_seed_cost;
    $form["#stat"]['#avg_fertilizer_cost'] = $statInfo->avg_fertilizer_cost;
    $form["#stat"]['#avg_pesticide_cost'] = $statInfo->avg_pesticide_cost;
    $form["#stat"]['#avg_machinery_cost'] = $statInfo->avg_machinery_cost;
    $form["#stat"]['#avg_others_cost'] = $statInfo->avg_others_cost;
    $form["#stat"]['#avg_general_yield'] = $statInfo->avg_general_yield;
    $form["#stat"]['#avg_other_yield'] = $statInfo->avg_other_yield;

    $query->limit(variable_get("list_page_item_number", 5));
    $plant_infoInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    if (get_user_role_name($user->uid) === '农户') {
        foreach ($plant_infoInfo as $row) {
            if (nonghua_user_access('plant_info', 'delete', $row->plant_info_id, $row->author_uid, $row->farmer_id)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }
            $rows[] = array(
                array('data' => "<input type='checkbox'".$disabled." value ='" . $row->plant_info_id . "' name='" . $row->plant_info_id . "'/>" . $n++, 'class' => 'integrant essential no'),
                array('data' => $row->plant_name, 'class' => ['integrant essential plant_name']),
                array('data' => $row->sow_date, 'class' => ['integrant essential break sow_date']),
                array('data' => $row->harvest_date, 'class' => ['essential break harvest_date']),
                array('data' => $row->plant_area, 'class' => ['integrant haveTobr essential break plant_area']),
                (isset($form_state['farmer']) && !empty($form_state['farmer'])) || (isset($form_state['addr_id']) && !empty($form_state['addr_id'])) ?
                    array('data' => '<a href="' . base_path() . 'farmer/plant_info/edit/' . $row->plant_info_id . '?farmer_id=' . $form_state['farmer'] . '" data-toggle="modal" target="_blank"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                    array('data' => '<a href="' . base_path() . 'farmer/plant_info/edit/' . $row->plant_info_id . '"  data-toggle="modal" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
//                array('data' => '<a href="' . base_path() . 'farmer/fertilization/list?plant_info_id=' . $row->plant_info_id . '" data-toggle="modal" target="_blank" class="btn btn-mini">施肥习惯</a>', 'class' => 'integrant essential delete fertilization'),
            );
        }
    } else {
        foreach ($plant_infoInfo as $row) {
            $city = $row->city ? ' ' . $row->city : '';
            $county = $row->county ? ' ' . $row->county : '';
            $town = $row->town ? ' ' . $row->town : '';
            $village = $row->village ? ' ' . $row->village : '';

            if (nonghua_user_access('plant_info', 'delete', $row->plant_info_id, $row->author_uid, $row->farmer_id)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }

            $rows[] = array(
                array('data' => "<input type='checkbox'".$disabled." value ='" . $row->plant_info_id . "' name='" . $row->plant_info_id . "'/>" . $n++, 'class' => 'integrant essential no'),
                isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? "" :
                    array('data' => $row->province . $city . $county . $town . $village, 'class' => ['integrant essential province city county']),
                isset($form_state['farmer']) && !empty($form_state['farmer']) ? "" :
                    array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id=' . $row->farmer_id . '">' . $row->farmer_name . '</a>', 'class' => ['integrant goRight essential farmer_name']),

                array('data' => $row->plant_name, 'class' => ['essential plant_name']),
                array('data' => $row->sow_date, 'class' => ['essential break sow_date']),
                array('data' => $row->harvest_date, 'class' => ['essential break harvest_date']),
                array('data' => $row->plant_area, 'class' => ['integrant haveTobr essential break plant_area']),
                (isset($form_state['farmer']) && !empty($form_state['farmer'])) || (isset($form_state['addr_id']) && !empty($form_state['addr_id'])) ?
                    array('data' => '<a href="' . base_path() . 'farmer/plant_info/edit/' . $row->plant_info_id . '?' .
                        (isset($form_state['addr_id']) && !empty($form_state['addr_id']) ? 'addr_id=' . $form_state['addr_id'] . '&' : '') .
                        (isset($form_state['farmer']) && !empty($form_state['farmer']) ? 'farmer_id=' . $form_state['farmer'] : '') .
                        '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                    array('data' => '<a href="' . base_path() . 'farmer/plant_info/edit/' . $row->plant_info_id . '"  target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own plant_info') ||  user_access('delete all plant_info'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'farmer/plant_info/export?'.$str.'&plant='.$form_state['values']['plant'].'&year='.$form_state['values']['year'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function plant_info_delete()
{
    ajax_table_delete('plant_info', 'plant_info_id');
}


function competitors_delete()
{
    ajax_table_delete('competitors', 'competitors_id');
}

function plant_info_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O');
    $tableheader = array('地址','农户姓名','农作物','播种日期','收货日期','种植面积', '农户电话');
    $data = get_plant_info_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'种植信息数据');
}

function get_plant_info_data($form = '', &$form_state = ''){
    global $user;
    $query = db_select('plant_info', 'PI');
    $query->join('farmer', 'F', 'F.farmer_id=PI.farmer_id');
    $query->join('plant', 'P', 'P.plant_id=PI.plant_id');
    $query->join('addr', 'A', 'F.addr_id=A.addr_id');


    $datestr = '';
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $datestr .= $form_state['values']['year'] . '-';
        }
    }
    if ($datestr) {
        $query->condition('PI.sow_date', db_like($datestr) . '%', 'LIKE');
    }
    if (get_user_role_name($user->uid) === '农户') {
        $query->condition('PI.farmer_id', $user->uid);
    } else {
        //地址级别查询
        if (!empty($_GET['village'])) {//乡镇级
            $query->condition('A.village_id', $_GET['village'], '=');
        } elseif (!empty($_GET['town'])) {//乡镇级
            $query->condition('A.town_id', $_GET['town'], '=');
        } elseif (!empty($_GET['county'])) {//县级
            $query->condition('A.county_id',$_GET['county'], '=');
        } elseif (!empty($_GET['city'])) {//市级
            $query->condition('A.city_id', $_GET['city'], '=');
        } elseif (!empty($_GET['province'])) {//省级
            $query->condition('A.province_id', $_GET['province'], '=');
        }
        if (!empty($form_state['values']['address_fuzzy'])) {
            $query->condition('A.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'LIKE');
        }
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('PI.farmer_id', $_GET['farmer']);
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('PI.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('PI.farmer_id', $form_state['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $form_state['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('PI.farmer_id',$_GET['farmer_id'], '=');
        }
        if(!user_access('view all plant_info') && user_access('view own plant_info')){
            $query->condition('PI.author_uid',$user->uid, '=');
        }
    }

    if(!empty($_GET['plant'])){
        $query->condition('PI.plant_id',$_GET['plant'], '=');
    }
    if (!empty($_GET['field'])) {
        if (!empty($_GET['min_number']) && !empty($_GET['max_number'])) {
            $db_and = db_and();
            $db_and->condition('PI.' . $_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('PI.' . $_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($_GET['min_number'])) {
            $query->condition('PI.' . $_GET['field'], $_GET['min_number'], '>');
        } elseif (!empty($_GET['max_number'])) {
            $query->condition('PI.' .$_GET['field'],$_GET['max_number'], '<');
        }
    }
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    $query->fields('PI',array('sow_date','harvest_date','plant_area'));
    $query->addField('F', 'cell');
    if(empty($form_state['values']) ) {
        $query->orderBy('PI.timestamp', 'DESC');
    }
    $plant_infoInfo = $query->execute()->fetchAll();
    foreach($plant_infoInfo as $k => $v){
        $plant_infoInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($plant_infoInfo[$k]->city);
        unset($plant_infoInfo[$k]->county);
        unset($plant_infoInfo[$k]->town);
        unset($plant_infoInfo[$k]->village);
    }
    return $plant_infoInfo;
}